package com.topvision.myviewtest.mvp.demo4.base.factory;

import com.topvision.myviewtest.mvp.demo4.base.presenter.BaseMvpPresenter;
import com.topvision.myviewtest.mvp.demo4.base.view.BaseMvpView;

/**
 * @author lucy
 * @date 2017-12-12 10:05
 * @description Presenter工厂实现类
 */

public class PresenterFactoryImpl<V extends BaseMvpView, P extends BaseMvpPresenter<V>> implements PresenterMvpFactory<V,P> {

    private Class<P> mPresenterClass;

    @Override
    public P createPresenter() {
        try {
            return mPresenterClass.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Presenter创建失败，检测是否声明注解");
        }
    }

    /**
     * 根据注解创建Presenter的工厂实现类
     *
     * @param viewClazz 需要创建Presenter的V层实现类
     * @param <V>       当前View实现的接口类型
     * @param <P>       当前要创建的Presenter类型
     * @return 工厂类
     */
    public static <V extends BaseMvpView, P extends BaseMvpPresenter<V>> PresenterMvpFactory<V, P> ctreateFactory(Class<?> viewClazz) {
        CreatePresenter presenter = viewClazz.getAnnotation(CreatePresenter.class);
        Class<P> aClass = null;
        if (presenter != null) {
            aClass = (Class<P>) presenter.value();
        }
        return aClass == null ? null : new PresenterFactoryImpl<V, P>(aClass);
    }

    private PresenterFactoryImpl(Class<P> aClass) {
        mPresenterClass = aClass;
    }
}
